package com.cliff.joinus.activity;

import java.util.ArrayList;

import org.cybergarage.upnp.Device;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnTouchListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.androidquery.callback.BitmapAjaxCallback;
import com.androidquery.util.AQUtility;
import com.cliff.joinus.Constants;
import com.cliff.joinus.LocalMediaDataManager;
import com.cliff.joinus.R;
import com.cliff.joinus.dataobject.ImageItem;

public class PlayImageActivity extends SherlockActivity implements
		OnTouchListener, OnGestureListener, OnItemClickListener {
	protected AQuery galleryAq = null;
	protected AQuery aq = null;
	protected GestureDetector myGestureDetector = null;

	protected int currentPos = 0;
	
	protected int screenX = 0;
	protected int screenY = 0;
	protected int x1 = 0;
	protected int y1 = 0;
	protected int x2 = 0;
	protected int y2 = 0;

	protected boolean isGalleryNavigating = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_playimage);

		aq = new AQuery(this);
		aq.id(R.id.imageViewFullScreen).getImageView().setOnTouchListener(this);
		// myGestureDetector = new
		// GestureDetector(aq.id(R.id.imageViewFullScreen).getImageView().getContext(),
		// this);
		myGestureDetector = new GestureDetector(this, this);

		currentPos = getIntent().getIntExtra(Constants.EXTRA_ITEMNODE_POS, 0);
		showCurrentImage(0);
		initGalleryView();
		aq.id(R.id.galleryImageView).gone();
	}

	protected void initGalleryView() {
		AQUtility.cleanCacheAsync(this, 0, 0);
		BitmapAjaxCallback.clearCache();

		galleryAq = new AQuery(this);

		ArrayList<ImageItem> list = LocalMediaDataManager.getInstance().getImageList();

		ArrayAdapter<ImageItem> aa = new ArrayAdapter<ImageItem>(this,
				R.layout.item_gallery_item, list) {
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.item_gallery_item, parent, false);
				}
				ImageItem item = getItem(position);
				String tbUrl = item.filePathName;
				AQuery aq = galleryAq.recycle(convertView);
				aq.id(R.id.textName).text(tbUrl);

				if (!aq.shouldDelay(position, convertView, parent, tbUrl)) {
					aq.id(R.id.tb).image(tbUrl, true, true, 100,
							R.drawable.image_missing, null, AQuery.FADE_IN,
							1.5f / 1.0f);
					aq.id(R.id.textName).text(tbUrl).gone();
				} else {
					aq.id(R.id.tb).clear();
					aq.id(R.id.textName).text(tbUrl).visible();
				}
//				Log.d("convertView ready", "PlayImageActivity");
				return convertView;
			}
		};
		galleryAq.id(R.id.galleryImageView).adapter(aa);
		galleryAq.id(R.id.galleryImageView).itemClicked(this);
		galleryAq.id(R.id.galleryImageView).getGallery()
				.setSelection(currentPos);

	}

	protected void initScreenParameter() {
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int abheight = getSherlock().getActionBar().getHeight();
		screenX = metrics.widthPixels;
		screenY = metrics.heightPixels - abheight;
//		Log.d("screenX=" + screenX + ";screenY=" + screenY + ";abheight="
//				+ abheight, "PlayImageActivity");

		x1 = screenX / 3;
		x2 = screenX - x1;
		y1 = x2 - x1;
		y2 = screenY - y1;
	}

//	@Override
//	protected void stopAndFinish() {
//		if ((havePlayed)&&(null != ControlPointManager.getInstance().getSelectedRenderer())) {
//			new AlertDialog.Builder(this)
//					.setIcon(android.R.drawable.ic_dialog_alert)
//					.setTitle(R.string.stop_playing)
//					.setMessage(R.string.really_stop_image)
//					.setPositiveButton(R.string.yes,
//							new DialogInterface.OnClickListener() {
//								@Override
//								public void onClick(DialogInterface dialog,
//										int which) {
//									ControlPointManager.getInstance()
//											.stopPlaying();
//									PlayImageActivity.this.finish();
//								}
//							})
//					.setNegativeButton(R.string.no,
//							new DialogInterface.OnClickListener() {
//								@Override
//								public void onClick(DialogInterface dialog,
//										int which) {
//									PlayImageActivity.this.finish();
//								}
//							}).show();
//		} else
//			finish();
//	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		initScreenParameter();
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (android.R.id.home == item.getItemId()) {
//			stopAndFinish();
			return true;
		}
		
		super.onOptionsItemSelected(item);
//		if (selectRendererSucceeded) {
//			if (ControlPointManager.getInstance().playImage(currentPos, false))
//				havePlayed = true;			
//		}
		
		return true;
	}

	protected boolean showCurrentImage(int offset) {
		ArrayList<ImageItem> list = LocalMediaDataManager.getInstance().getImageList();
		int size = list.size();
		int destPos = currentPos + offset;
		if ((destPos < 0) || (destPos >= size)) {
			Toast.makeText(this, "over", Toast.LENGTH_SHORT)
					.show();
			return false;
		}
		currentPos = destPos;

		ImageItem item = list.get(currentPos);
		
		setTitle(getString(R.string.section_localmedia_images) + " > "
				+ (currentPos+1) + "/" + size);
//		setTitle(getString(R.string.section_localmedia_images) + ">"
//				+ fileName.substring(fileName.lastIndexOf("/") + 1));
		aq.id(R.id.imageViewFullScreen)
				.progress(R.id.progress)
				.image(item.filePathName, false, true, screenX,
						R.drawable.image_missing, null, AQuery.FADE_IN);
//		mediator.
//		if (ControlPointManager.getInstance().playImage(currentPos, false))
//			havePlayed = true;
		return true;
	}

	@Override
	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		// if (e1.getX() - e2.getX() > 120) {
		//
		// }
		return false;
	}

	@Override
	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onSingleTapUp(MotionEvent event) {
		// TODO Auto-generated method stub
		int x = (int) event.getX();
		int y = (int) event.getY();
//		Log.d("onSingleTapUp x=" + x + ";y=" + y + ";x1=" + x1 + ";x2=" + x2
//				+ ";y1=" + y1 + ";y2=" + y2, "PlayImageActivity");

		if (x < x1) {
			showCurrentImage(-1);
		} else if (x > x2) {
			showCurrentImage(1);
		} else if (y < y1) {
			showCurrentImage(-1);
		} else if (y > y2) {
			showCurrentImage(1);
		} else {
			// Toast.makeText(this, "middle", Toast.LENGTH_SHORT).show();
//			Log.d("ready to show/hide with isGalleryNavigating="
//					+ isGalleryNavigating, "PlayImageActivity");
			if (isGalleryNavigating)
				aq.id(R.id.galleryImageView).gone();
			else
				aq.id(R.id.galleryImageView).visible();
			isGalleryNavigating = !isGalleryNavigating;
		}
		aq.id(R.id.galleryImageView).getGallery().setSelection(currentPos);
		return true;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		myGestureDetector.onTouchEvent(event);
		return true;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		currentPos = position;
		showCurrentImage(0);
	}

}
